package cn.xyw.solrCloud;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;

import java.io.IOException;

/**
 * @author Evan
 * @Title: testCreate
 * @ProjectName solr
 * @Description: TODO
 * @date 2018/7/816:11
 */
public class testCreate {

    @Test
    public void testWrite() throws IOException, SolrServerException {
        // 创建SolrServer
        CloudSolrServer server = new CloudSolrServer("192.168.206.101:2181,192.168.206.102:2181,192.168.206.103:2181");
        // 指定要访问的Collection名称
        server.setDefaultCollection("myCollection1");

        // 创建Document对象
        SolrInputDocument document = new SolrInputDocument();
        // 添加字段
        document.addField("id","20");
        document.addField("title","宝马x6,你值得拥有");

        // 添加Document到Server
        server.add(document);

        // 提交
        server.commit();


    }

    @Test
    public void testSearch() throws IOException, SolrServerException {
        // 创建SolrServer
        CloudSolrServer server = new CloudSolrServer("192.168.206.101:2181,192.168.206.102:2181,192.168.206.103:2181");
        // 指定要访问的Collection名称
        server.setDefaultCollection("myCollection1");

       // 查找数据
        QueryResponse query = server.query(new SolrQuery("id:20"));

        // 以document形式解析数据
        SolrDocumentList documentList = query.getResults();

        // 遍历
        for (SolrDocument solrDocument : documentList) {
            System.out.println(solrDocument.getFieldValue("id"));
            System.out.println(solrDocument.getFieldValue("title"));
        }

    }

    @Test
    public void testDelete() throws Exception{
        // 创建SolrServer
        CloudSolrServer server = new CloudSolrServer("192.168.206.101:2181,192.168.206.102:2181,192.168.206.103:2181");
        // 指定要访问的Collection名称
        server.setDefaultCollection("myCollection1");
        // 根据ID删除
        server.deleteById("20");
        // 提交
        server.commit();
    }


}
